package com.hsh.server.util.redis;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.HexUtil;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Date;

public class JwtWithHutoolExample {

    // 密钥，这里以字符串形式表示，实际应用中应从安全的地方加载
    private static final String SECRET = "your-256-bit-secret";

    // 使用 HMAC-SHA256 算法
    private static Algorithm getAlgorithm() {
        return Algorithm.HMAC256(SECRET);
    }

    // 生成 JWT
    public static String generateJwt(String subject) {
        return JWT.create()
                .withSubject(subject)
                .withIssuedAt(new Date())
                .withExpiresAt(new Date(System.currentTimeMillis() + 7200 * 3600 * 1000))
                .sign(getAlgorithm());
    }
    public static String generateJwt(String subject, long expirationMillis) {
        return JWT.create()
                .withSubject(subject)
                .withIssuedAt(new Date())
                .withExpiresAt(new Date(System.currentTimeMillis() + expirationMillis))
                .sign(getAlgorithm());
    }

    // 解析 JWT
    public static DecodedJWT verifyJwt(String token) {
        try {
            return JWT.require(getAlgorithm())
                    .build()
                    .verify(token);
        } catch (JWTVerificationException exception){
            // Token无效
            System.out.println("Token验证失败: " + exception.getMessage());
            return null;
        }
    }





    public static void main(String[] args) {
        try {
//            // 生成对称密钥（仅示例，实际应用中应使用安全的密钥管理方式）
//            String secret = "your-256-bit-secret";
//
//            // 生成 JWT
//            String token = generateJwt("user123", 7200 * 3600 * 1000); // 1小时过期
//            System.out.println("生成的 JWT: " + token);
//
//            // 解析 JWT
//            DecodedJWT decodedJWT = verifyJwt(token);
//            if (decodedJWT != null) {
//                System.out.println("Token有效。");
//                System.out.println("Subject: " + decodedJWT.getSubject());
//                System.out.println("Expires at: " + decodedJWT.getExpiresAt());
//            }
//            DecodedJWT decodedJWT = verifyJwt("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIiwiZXhwIjoxNzQzMjk1MjU0LCJpYXQiOjE3NDMxNDUwNTh9.4K2sl-iaGiALQarK9l0rDXrc9-wRVVkwjBRXPh7ZRhY");
//            System.out.println(decodedJWT);
            // 如果使用非对称加密，示例如下：

            // 生成 RSA 密钥对（需要使用 KeyPairGenerator）
            /*
            KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
            keyGen.initialize(2048);
            KeyPair keyPair = keyGen.generateKeyPair();
            PrivateKey privateKey = keyPair.getPrivate();
            PublicKey publicKey = keyPair.getPublic();

            String rsaToken = generateJwtWithRsaPrivateKey("user456", 3600 * 1000, privateKey);
            System.out.println("生成的 RSA JWT: " + rsaToken);

            DecodedJWT rsaDecodedJWT = verifyJwtWithRsaPublicKey(rsaToken, publicKey);
            if (rsaDecodedJWT != null) {
                System.out.println("RSA Token有效。");
                System.out.println("Subject: " + rsaDecodedJWT.getSubject());
                System.out.println("Expires at: " + rsaDecodedJWT.getExpiresAt());
            }
            */



        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}